package cn.south.campus.business.service.impl;

import cn.south.campus.business.mapper.PartTimeJobApplyMapper;
import cn.south.campus.business.model.bo.LoginContext;
import cn.south.campus.business.model.entity.PartTimeJobApply;
import cn.south.campus.business.service.PartTimeJobApplyService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 校园兼职申请表 服务实现类
 * </p>
 *
 * @author chow
 * @since 2025-03-27
 */
@Service
@AllArgsConstructor
public class PartTimeJobApplyServiceImpl extends ServiceImpl<PartTimeJobApplyMapper, PartTimeJobApply> implements PartTimeJobApplyService {

    private final PartTimeJobApplyMapper partTimeJobApplyMapper;

    @Override
    public int checkApply(Long partTimeJobId) {
        LambdaQueryWrapper<PartTimeJobApply> wrapper = new LambdaQueryWrapper<PartTimeJobApply>()
                .eq(PartTimeJobApply::getUserId, LoginContext.getContext().getId())
                .eq(PartTimeJobApply::getJobId, partTimeJobId);
        PartTimeJobApply timeJobApply = partTimeJobApplyMapper.selectOne(wrapper);
        if (timeJobApply == null) {
            return -1;
        }
        return timeJobApply.getStatus();
    }

    @Override
    public Map<Long, Integer> queryApplyCount(List<Long> partTimeJobIds) {
        String jobId = "job_id";
        QueryWrapper<PartTimeJobApply> wrapper = new QueryWrapper<PartTimeJobApply>()
                .in(jobId, partTimeJobIds)
                .groupBy(jobId)
                .select(jobId, "count(1) as cnt");
        List<Map<String, Object>> mapList = partTimeJobApplyMapper.selectMaps(wrapper);
        if (CollectionUtils.isEmpty(mapList)) {
            return new HashMap<>();
        }
        Map<Long, Integer> hashMap = new HashMap<>();
        for (Map<String, Object> map : mapList) {
            hashMap.put(Long.valueOf(String.valueOf(map.get(jobId))), Integer.valueOf(String.valueOf(map.get("cnt"))));
        }
        return hashMap;
    }

    @Override
    public void cancelApply(Long id) {
        LambdaQueryWrapper<PartTimeJobApply> wrapper = new LambdaQueryWrapper<PartTimeJobApply>()
                .eq(PartTimeJobApply::getUserId, LoginContext.getContext().getId())
                .eq(PartTimeJobApply::getJobId, id);
        partTimeJobApplyMapper.delete(wrapper);
    }
}
